package benny.ApkposStore.Activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.Adapter.cookAdapter;
import benny.ApkposStore.Adapter.cookAdapter.Cooklistholder;
import benny.ApkposStore.Adapter.cookselectAdapter;
import benny.ApkposStore.Adapter.cookselectAdapter.Cookselectholder;
import benny.ApkposStore.Adapter.dishpotlistAdapter.Dishpotlistholder;
import benny.ApkposStore.db.ConfigDBHelper;
import benny.ApkposStore.db.DBHelper;
import benny.ApkposStore.db.OrderTableDishs;
import benny.ApkposStore.db.OrderZuoflist;
import benny.ApkposStore.model.DishNew;
import benny.ApkposStore.model.Make_tbl;
import benny.ApkposStore.model.Zuoflist;
import benny.ApkposStore.utils.ApkConfigdbUntils;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkDbUntils;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.Rotate3dAnimation;

//import com.tencent.elife.asyn.BaseManager;
//import com.tencent.elife.asyn.Command;
//import com.tencent.elife.asyn.DataResponse;

public class ZuofActivity extends Activity {
	private String room_name;
	private String room_id;
	private String orderid;
	private int peoplenum;
	private String dish_id;
	private String cooktitle;
	private String dpriflo_now;
	private String dishnum_now;
	private String ddet_now;
	private String dishpricestr;
	private String countchange;
	private String ordertype;
	private ListView cookselectListview;
	private List<Zuoflist> zuofselectllist;
	private cookselectAdapter cookselectAdapter;
	private int cooklist_heightdip;
	private int cooklistview_height;
	private int cooklist_heightpx = 28;
	private Resources resources;
	private ListView cooklistView;
	private List<Make_tbl> maketbllist;
	private List<Make_tbl> searchmaketbllist;
	private cookAdapter cooklistAdapter = null;
	private SimpleAdapter cooksearchAdapter;
	private AutoCompleteTextView cooksearch;
	protected Drawable mIconSearchDefault;
	protected Drawable mIconSearchClear;
	private TextView dishcooktitle;
	private TextView dishprice;
	private Button cookviewclose;
	private Button cookviewbtn1;
	private Button cookviewbtn2;
	private TextView dishordertype;
	private Button cookviewbtn3;
	private Button cookviewbtn4;
	private GridView powgridView;
	private EditText dishcountchange;
	private ListAdapter menuAdapter;
	private SQLiteDatabase db;
	private SQLiteDatabase configdb;
	private int pagetotal;
	private int pagenow = 0;
	public int lastItem = 0;
	private ScrollView cookScrollview;
	private LinearLayout cooklistLayout;
	private ProgressBar main_progessbarn;;
	private int index = 0;
	private int mLastY = 0;
	private int itemnum = 40;
	private Context mcx =null;
	private String sqlstr ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.dishcookview);
		menuAdapter = ApkUntils.getMenuAdapter(this);
		// DataManager.instance().init(getApplicationContext());
		mcx=getApplicationContext();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();// 根据bundle的key得到对应的对象
		room_name = bundle.getString("room_name");
		room_id = bundle.getString("room_id");
		orderid = bundle.getString("orderid");
		peoplenum = bundle.getInt("people_num");
		dish_id = bundle.getString("dish_id");
		cooktitle = bundle.getString("cooktitle");
		dpriflo_now = bundle.getString("dpriflo_now");
		dishnum_now = bundle.getString("dishnum_now");
		ddet_now = bundle.getString("ddet_now");
		dishpricestr = bundle.getString("dishpricestr");
		countchange = bundle.getString("countchange");
		ordertype = bundle.getString("ordertype");
		resources = getResources();
		mIconSearchDefault = resources
				.getDrawable(R.drawable.txt_search_default);
		mIconSearchClear = resources.getDrawable(R.drawable.txt_search_clear);

		TextView roomname = (TextView) findViewById(R.id.roomtext);
		TextView people = (TextView) findViewById(R.id.peoplenumtext);
		TextView ordersid = (TextView) findViewById(R.id.ordersid);
		roomname.setText(room_name);
		ordersid.setText("NO." + orderid);
		people.setText(peoplenum + "");

		// ////已选做法列表
		cookselectListview = (ListView) findViewById(R.id.cookselectList);
		cooklist_heightdip = ApkUntils.convertPX2DIP(this, cooklist_heightpx
				* ApkUntils.getPixelsintH(this));
		resources = getResources();
		cookselectListview.setSelector(R.color.transparent);
		cookselectListview.setDivider(resources.getDrawable(R.drawable.hline));
		cookselectListview.setDividerHeight(ApkUntils.convertPX2DIP(this,
				3 * ApkUntils.getPixelsintH(this)));
		cookselectListview.setOnItemClickListener(new selectListviewListener());
		// 加载数据
		showcookselectlist();
		
		cooklist_heightdip = ApkUntils.convertPX2DIP(this, cooklist_heightpx
				* ApkUntils.getPixelsintH(this));
		maketbllist=Apkglobal.getmaketbllist();
		if (maketbllist== null) {

			maketbllist = updatemakelist();
			Apkglobal.setmaketbllist(maketbllist);
			searchmaketbllist = maketbllist;
			cooksearchAdapter = cookserchAdapter(searchmaketbllist,
					R.layout.serchdishbtn);
		} else {
			searchmaketbllist = maketbllist;
			cooksearchAdapter = cookserchAdapter(searchmaketbllist,
					R.layout.serchdishbtn);
		
		}	

		// ////////////做法选择列表
		cookScrollview = (ScrollView) findViewById(R.id.cookScrollview);
		cooklistLayout = (LinearLayout) findViewById(R.id.cooklistLayout);
		main_progessbarn = (ProgressBar) findViewById(R.id.main_progessbar);
		cooklistView = (ListView) findViewById(R.id.cookListview);
		resources = getResources();
		cooklistView.setDivider(resources.getDrawable(R.drawable.hline));
		cooklistView.setDividerHeight(ApkUntils.convertPX2DIP(this,
				3 * ApkUntils.getPixelsintH(this)));
		cooklistView.setSelector(R.color.transparent);
		cooklistView.setOnItemClickListener(new zuoflistListener());
		cookScrollview.setOnTouchListener(new zuoftouchListener());

		// ////////////////////////////////////
		// 绑定搜索框cooksearch事件
		cooksearch = (AutoCompleteTextView) findViewById(R.id.cooksearch);
		// autosearch.setInputType(InputType.TYPE_NULL);
		cooksearch.setCompoundDrawablesWithIntrinsicBounds(null, null,
				mIconSearchDefault, null);
		cooksearch.setOnKeyListener(new cooksearchOnkeyListener());
		cooksearch.setThreshold(1);
		cooksearch.setHint("请输入做法名称或检索码");
		cooksearch.setOnItemClickListener(new cooksearchItemClickListener());
		cooksearch.setOnTouchListener(new cooksearchOnTouchListener());
		// autosearch.setOnItemSelectedListener(new
		// autosearchselectClickListener());
		cooksearch.setAdapter(cooksearchAdapter);
		cooksearch.addTextChangedListener(new TextWatcher() {
			private boolean isnull = true;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				cooksearch.setThreshold(1);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(s)) {
					if (!isnull) {
						cooksearch.setCompoundDrawablesWithIntrinsicBounds(
								null, null, mIconSearchDefault, null);
						isnull = true;
					}
				} else {
					if (isnull) {
						cooksearch.setCompoundDrawablesWithIntrinsicBounds(
								null, null, mIconSearchClear, null);
						isnull = false;
					}
				}

			}
		});
		// //////////////////////////////////

		dishcooktitle = (TextView) findViewById(R.id.dishcooktitle); // 取得组件
		dishcooktitle.setHint(dish_id);
		dishcooktitle.setText(cooktitle);
		dishprice = (TextView) findViewById(R.id.dishprice); // 取得组件
		dishprice.setText(dishpricestr);

		dishordertype = (TextView) findViewById(R.id.dishordertype); // 取得组件
		dishordertype.setText(ordertype);

		cookviewclose = (Button) findViewById(R.id.cookviewclose); // 取得组件
		cookviewclose.setTag(10);
		cookviewbtn1 = (Button) findViewById(R.id.cookviewbtn1); // 取得组件
		cookviewbtn1.setTag(1);
		cookviewbtn2 = (Button) findViewById(R.id.cookviewbtn2); // 取得组件
		cookviewbtn2.setTag(2);
		cookviewbtn3 = (Button) findViewById(R.id.cookviewbtn3); // 取得组件
		cookviewbtn3.setTag(3);
		cookviewbtn4 = (Button) findViewById(R.id.cookviewbtn4); // 取得组件
		cookviewbtn4.setTag(4);
		Button dishadd = (Button) findViewById(R.id.dishadd); // 取得组件
		dishadd.setTag(5);
		Button dishdel = (Button) findViewById(R.id.dishdel); // 取得组件
		dishdel.setTag(6);
		dishadd.setOnClickListener(new cookviewbtnListener());
		dishdel.setOnClickListener(new cookviewbtnListener());
		cookviewbtn1.setOnClickListener(new cookviewbtnListener());
		cookviewbtn2.setOnClickListener(new cookviewbtnListener());
		cookviewbtn3.setOnClickListener(new cookviewbtnListener());
		cookviewbtn4.setOnClickListener(new cookviewbtnListener());
		cookviewclose.setOnClickListener(new cookviewbtnListener());

		powgridView = (GridView) findViewById(R.id.gridview_softkeyboard);

		dishcountchange = (EditText) findViewById(R.id.dishcountchange);
		dishcountchange.setText(countchange);
		dishcountchange.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(s)) {
					dishcountchange.setText("0");
				}

			}
		});

		dishcountchange.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					dishcountchange.selectAll();
					break;
				case MotionEvent.ACTION_UP:
					ApkUntils.opensoftkeyboard(dishcountchange, powgridView,
							menuAdapter, 1);
					ApkUntils.keyboardtouchup(dishcountchange, powgridView,
							menuAdapter, getApplicationContext());

					break;
				default:
					break;
				}

				return false;
			}
		});

		dishcountchange.setTag(1);
		dishcountchange.setInputType(InputType.TYPE_NULL);

		// 创建一个PopuWidow对象

	}

	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		System.gc(); // 回收系统资源
		super.onDestroy();
	}

	private List<Make_tbl> updatemakelist() {

		configdb = ConfigDBHelper.getReadableDatabase(mcx,
				"shop_config.db");
		Cursor cursor;

		cursor = configdb.rawQuery(
				"select * from config_cook_method order by rank_id", null);
		System.out.println(cursor.getCount());

		ArrayList<Make_tbl> data = new ArrayList<Make_tbl>();
		while (cursor.moveToNext()) {

			Make_tbl make_tbl = new Make_tbl();
			make_tbl.setCook_class(cursor.getInt(cursor
					.getColumnIndex("cook_class")));
			make_tbl.setId(cursor.getInt(cursor.getColumnIndex("id")));
			make_tbl.setIs_charge(cursor.getInt(cursor
					.getColumnIndex("is_charge")));
			make_tbl.setCook_price(cursor.getInt(cursor
					.getColumnIndex("cook_price")));
			make_tbl.setIs_show_kitchen(cursor.getInt(cursor
					.getColumnIndex("is_show_kitchen")));
			make_tbl.setNumber_statistic_class(cursor.getInt(cursor
					.getColumnIndex("number_statistic_class")));
			make_tbl.setRank_id(cursor.getInt(cursor.getColumnIndex("rank_id")));

			make_tbl.setCook_name(cursor.getString(cursor
					.getColumnIndex("cook_name")));
			make_tbl.setCook_unit(cursor.getString(cursor
					.getColumnIndex("cook_unit")));
			make_tbl.setRetrieval_code(cursor.getString(cursor
					.getColumnIndex("retrieval_code")));

			data.add(make_tbl);
		}
		cursor.close();

		return data;

	}

	private SimpleAdapter cookserchAdapter(List<Make_tbl> list, int layout) {
		SimpleAdapter simpleAdapter = null;
		List<HashMap<String, String>> dishtypes = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", list.get(i).getCook_name());
			map.put("zuof_var", list.get(i).getId() + "");
			map.put("danw", list.get(i).getCook_unit());
			map.put("pricflo", list.get(i).getCook_price() + "");
			map.put("jsmm", list.get(i).getRetrieval_code());
			map.put("id", "#" + i);
			map.put("serch", list.get(i).getRetrieval_code() + " "
					+ list.get(i).getId());
			dishtypes.add(map);
		}
		simpleAdapter = new SimpleAdapter(this, dishtypes, layout,
				new String[] { "name", "serch", "id" }, new int[] {
						R.id.serchdishname, R.id.search, R.id.listid });
		return simpleAdapter;
	}

	private List<Zuoflist> queryzuoflist(String orderid, String dish_id,
			String subdish_id) {
		// TODO Auto-generated method stub
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		List<Zuoflist> data = new ArrayList<Zuoflist>();
		String selection;
		try {
			OrderZuoflist orderzuoflist = new OrderZuoflist(
					getApplicationContext());
			selection = "orderid=? and dish_id=? and subdish_id=?";
			String selectionArgs[] = { orderid, dish_id, subdish_id };
			Cursor curSor = orderzuoflist.getCurSor(selection, selectionArgs);

			while (curSor.moveToNext()) {
				data.add(orderzuoflist.CurSorToGasBean(curSor));

			}
			curSor.close();
			// System.out.println(data);

		} catch (SQLiteException e) {
			Log.e("apkpos_orders_zuoflist",
					"queryzuoflist  error:" + e.getMessage());
		}

		return data;
	}

	private void deletezuoflist(String orderid, String dish_id,
			String subdish_id, String zuof_id) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		float num = 0;
		Cursor cursor;

		cursor = db.query("apkpos_orders_zuoflist",
				new String[] { "ifnull(sl,0) as sl" },
				"orderid=? and dish_id=? and subdish_id=? and zuof_id=?",
				new String[] { orderid, dish_id, subdish_id, zuof_id }, null,
				null, null);
		while (cursor.moveToNext()) {
			num = cursor.getFloat(cursor.getColumnIndex("sl"));

		}

		try {
			if (num > 1) {
               
				sqlstr="  update  apkpos_orders_zuoflist set sl=sl-1,jine=(sl-1)*jiag where  orderid='"
						+ orderid
						+ "' and dish_id="
						+ dish_id
						+ " and subdish_id="
						+ subdish_id
						+ " and zuof_id="
						+ zuof_id + "   ";

			} else {

				sqlstr="  delete from  apkpos_orders_zuoflist where  orderid='"
						+ orderid
						+ "' and dish_id="
						+ dish_id
						+ " and subdish_id="
						+ subdish_id
						+ " and zuof_id="
						+ zuof_id + "   ";

			}
			execSQL(db, mcx, sqlstr);

		} catch (Exception e) {
			Log.e("apkpos_orders_zuoflist",
					"delete apkpos_orders_zuoflist error:" + e.getMessage());

		}
		cursor.close();
	}

	private void addzuoflist(String orderid, String dish_id, String subdish_id,
			String zuof_id) {

		try {
			sqlstr="  update  apkpos_orders_zuoflist set sl=sl+1,jine=(sl+1)*jiag where  orderid='"
					+ orderid
					+ "' and dish_id="
					+ dish_id
					+ " and subdish_id="
					+ subdish_id + " and zuof_id=" + zuof_id + "   ";
			
			execSQL(db, mcx, sqlstr);
		} catch (Exception e) {
			Log.e("apkpos_orders_zuoflist", "add apkpos_orders_zuoflist error:"
					+ e.getMessage());

		}
		

	}
	
	
	private void updatecook_content(String orderid, String dish_id, int subdish_id) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		Cursor cursor;
		sqlstr="select * from apkpos_orders_zuoflist where orderid='"+orderid+"' and dish_id="+dish_id+"" +
				" and subdish_id="+subdish_id+"";
		cursor=db.rawQuery(sqlstr, null);
		String cook_content = "";
		float extra=0;
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				 String dw = cursor.getString(cursor.getColumnIndex("dw"));
				 String mingc = cursor.getString(cursor.getColumnIndex("mingc"));
				 String sl = cursor.getString(cursor.getColumnIndex("sl"));
				 extra = extra+cursor.getFloat(cursor.getColumnIndex("jine"));
				 if ((dw!=null) && (!dw.equals(""))) {
					 cook_content=cook_content+"("+mingc+sl+dw+")";
				}
				 else {
					 cook_content=cook_content+"("+mingc+")";
				}			
			}	
		}
		cursor.close();
		
		try {
		     if (subdish_id>0) {
		    	 sqlstr="  update  apkpos_orders_subdishs set cook_content='"+cook_content+"', cook_extra='"+extra+"'" +
		    	 		" where orderid='"+orderid+"' and dish_id="+dish_id+" and  subdish_id="
					+ subdish_id + "";
			}
		     else {
		    	 sqlstr="  update  apkpos_orders_dishs set cook_content='"+cook_content+"', cook_extra='"+extra+"'" +
			    	 		" where orderid='"+orderid+"' and dish_id="+dish_id+"";
			}
					
			ApkUntils.execSQL(mcx, sqlstr);
		} catch (Exception e) {
			Log.e("apkpos_orders_zuoflist", "updatecook_content error:"
					+ e.getMessage());

		}

	}

	private void insertzuoflist(String orderid, String dish_id,
			String subdish_id, float sl, float jiag, String dw, String mingc) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		String zuof_id = "";
		float num = 0;
		Cursor cursor;
		cursor = db.query("apkpos_orders_zuoflist",
				new String[] { "zuof_id,ifnull(sl,0) as sl" },
				"orderid=? and dish_id=? and subdish_id=? and mingc=?",
				new String[] { orderid, dish_id, subdish_id, mingc }, null,
				null, null);
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				num = cursor.getFloat(cursor.getColumnIndex("sl"));
				zuof_id = cursor.getString(cursor.getColumnIndex("zuof_id"));
			}
			if (num > 0) {
				try {
					sqlstr="  update  apkpos_orders_zuoflist set sl=sl+1,jine=(sl+1)*jiag where  orderid='"
							+ orderid
							+ "' and dish_id="
							+ dish_id
							+ " and subdish_id="
							+ subdish_id
							+ " and zuof_id="
							+ zuof_id + "   ";
					execSQL(db, mcx, sqlstr);
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				Toast.makeText(this, "该做法已经被选择，无需重复操作！", Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			cursor = db.query("apkpos_orders_zuoflist",
					new String[] { "ifnull(max(zuof_id),0)+1 as aaa" },
					"orderid=? and dish_id=? and subdish_id=?", new String[] {
							orderid, dish_id, subdish_id }, null, null, null);
			while (cursor.moveToNext()) {
				zuof_id = cursor.getString(cursor.getColumnIndex("aaa"));

			}

			try {
				sqlstr="insert into apkpos_orders_zuoflist(orderid,dish_id,subdish_id,zuof_id,"
						+ "sl,jiag,jine,dw,mingc)"
						+ " values ('"
						+ orderid
						+ "',"
						+ dish_id
						+ ",'"
						+ subdish_id
						+ "','"
						+ zuof_id
						+ "',"
						+ ApkUntils
								.convertFloat(sl + "", ApkConstant.FLOAT_NUM)
						+ ","
						+ ApkUntils.convertFloat(jiag + "",
								ApkConstant.FLOAT_NUM)
						+ ","
						+ ApkUntils.convertFloat(jiag * sl + "",
								ApkConstant.FLOAT_NUM)
						+ ",'"
						+ dw
						+ "','"
						+ mingc + "')";
				
				execSQL(db, mcx, sqlstr);
			} catch (SQLiteException e) {
				Log.e("apkpos_orders_zuoflist",
						"insert apkpos_orders_zuoflist error:" + e.getMessage());
			}
		}

		cursor.close();

	}

	class zuoftouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				index++;
				break;
			default:
				break;
			}
			if (event.getAction() == MotionEvent.ACTION_UP && index > 0) {
				index = 0;

				mLastY = cookScrollview.getScrollY();// 赋值给mLastY
				if (mLastY == 0) {
					// 滑动到顶部
					if (pagenow >= 1) {
						Asyncgetnext asyncgetnext = new Asyncgetnext();
						asyncgetnext.setflag(2);
						asyncgetnext.execute();
					}
				}

				if (mLastY == (cooklistLayout.getHeight() - cookScrollview
						.getHeight())) {
					// TODO
					// 滑动到底部
					if (pagenow <= pagetotal) {
						Asyncgetnext asyncgetnext = new Asyncgetnext();
						asyncgetnext.setflag(0);
						asyncgetnext.execute();

					}
				}
			}
			return false;
		}

	}

	// 异步加载做法
	private class Asyncgetnext extends AsyncTask<Void, Void, Integer> {
		private String msg = "加载失败！";
		private int flagnum = 0;

		public void setflag(int flag) {
			flagnum = flag;
		}

		@Override
		protected Integer doInBackground(Void... params) {

			try {
				if ((pagenow==1)||(pagenow==pagetotal) ) {
				     return 0;	
				}
				maketbllist = ApkConfigdbUntils.updatemakelistlimit(
						getApplicationContext(), pagenow * itemnum - flagnum
								* itemnum, itemnum);

				if (pagenow == pagetotal - 1) {
					cooklistview_height = cooklist_heightdip
							* maketbllist.size();

				}
				Log.e("size", "Asyncgetnext:" + maketbllist.size());
			} catch (Exception e) {
				Log.e("", "Asyncgetnext:" + e.getMessage());
				msg = "加载失败！" + e.getMessage();
				return -1;
			}

			return 0;
		}

		// 在doInBackground前执行
		protected void onPreExecute() {
			// TODO: 显示正在登陆的提示

			main_progessbarn.setVisibility(View.VISIBLE);

		}

		// 在doInBackground后执行
		protected void onPostExecute(Integer result) {
			main_progessbarn.setVisibility(View.GONE);
			if (result == 0) {
				if ((pagenow==1) &&(flagnum!= 0)) {
					Toast.makeText(ZuofActivity.this, "最上一页！", Toast.LENGTH_SHORT)
					.show();
					return;
				}
				else if ((pagenow==pagetotal) &&(flagnum== 0))  {
					Toast.makeText(ZuofActivity.this, "最后一页！", Toast.LENGTH_SHORT)
					.show();
					return;
				}
				cooklistAdapter = new cookAdapter(ZuofActivity.this,
						maketbllist);
				cooklistView.setAdapter(cooklistAdapter);
				int count=cooklistAdapter.getCount(); 
				if ( count!= itemnum) {
					ApkUntils.changeviewlayout(cooklistView, 0,
							cooklistview_height, cooklistAdapter);
				}
				if (flagnum == 0) {
					cookScrollview.scrollTo(1, 1);
					pagenow++;
				} else {
					cookScrollview.scrollTo(1,cooklistLayout.getHeight() - cookScrollview
					.getHeight());
					pagenow--;
				}

			} else {
				// TODO: login failed，取消正在登陆的提示，换成提示登陆失败
				Toast.makeText(ZuofActivity.this, msg, Toast.LENGTH_SHORT)
						.show();
			}

		}
	}


	private void getnextAdapter(int offset, int count) {

		maketbllist = ApkConfigdbUntils.updatemakelistlimit(getApplicationContext(), offset, count);
		cooklistAdapter = new cookAdapter(this, maketbllist);
		if (pagenow == pagetotal - 1) {
			cooklistview_height = cooklist_heightdip
					* cooklistAdapter.getCount();
			ApkUntils.changeviewlayout(cooklistView, 0, cooklistview_height,
					cooklistAdapter);
			if (Apkglobal.getcurrentapiVersion() > 10) {
				cooklistView.setAdapter(cooklistAdapter);
			}
		} else {
			cooklistView.setAdapter(cooklistAdapter);
		}

	}

	private void showcooklist() {
		int count=maketbllist.size();

		if (count>itemnum) {
			pagetotal = (int) Math.ceil(maketbllist.size() / itemnum);
			pagenow = 0;
			cooklistview_height = cooklist_heightdip
					* itemnum;
		}
         else {
 			pagenow = 0;
			pagetotal = 1;
		}
		Asyncgetnext asyncgetnext=new Asyncgetnext();
		asyncgetnext.setflag(0);
		asyncgetnext.execute();
	}
	
	

	// 创建setupdishlistView按下监听事件
	class zuoflistListener implements OnItemClickListener {

		private Cooklistholder cooklistholder = null;
		private float sl = 0;
		private String dw;
		private float jiag;
		private String mingc;

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			cooklistholder = (Cooklistholder) view.getTag();
			System.out.println(position);
			dw = cooklistholder.danw;
			jiag = cooklistholder.pric;
			mingc = cooklistholder.mingc;
			if ((!dw.equals(""))||(jiag>0.01)) {
				sl = 1;
			}
			cooklistholder.cookitem5.startchange();
			insertzuoflist(orderid, dish_id, "0", sl, jiag, dw, mingc);
			showcookselectlist();		
			// jine = sl * jiag;
//			cooklistholder.cookitem5.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//					// TODO Auto-generated method stub
//					insertzuoflist(orderid, dish_id, "0", sl, jiag, dw, mingc);
//					cooklistholder.cookitem5.startchange();
//					showcookselectlist();
//					System.out.println("item:"+cooklistholder.position);
//					/*
//					 * Toast.makeText(DishordersActivity.this, "点击了第" + aaa +
//					 * "加1按钮", Toast.LENGTH_SHORT) .show();
//					 */
//				}
//			});

		}
	}

	// 创建setupdishlistView按下监听事件
	class selectListviewListener implements OnItemClickListener {

		private Cookselectholder cookselectholder = null;
		private String zuof_id;

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			cookselectholder = (Cookselectholder) view.getTag();
			zuof_id = cookselectholder.ZUOF_ID;
			cookselectholder.cookitem4
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							cookselectholder.cookitem4.startchange();
							addzuoflist(orderid, dish_id, "0", zuof_id);
							showcookselectlist();

						}
					});

			cookselectholder.cookitem5
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							cookselectholder.cookitem5.startchange();
							deletezuoflist(orderid, dish_id, "0", zuof_id);
							showcookselectlist();
							/*
							 * Toast.makeText(DishordersActivity.this, "点击了第" +
							 * aaa + "加1按钮", Toast.LENGTH_SHORT) .show();
							 */
						}
					});

		}
	}

	private void showcookselectlist() {
		zuofselectllist = queryzuoflist(orderid, dish_id, "0");
		cookselectAdapter = new cookselectAdapter(this, zuofselectllist);
		int count = cookselectAdapter.getCount();
		cooklistview_height = cooklist_heightdip * count;
		ApkUntils.changeviewlayout(cookselectListview, 0, cooklistview_height,
				cookselectAdapter);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			cookselectListview.setAdapter(cookselectAdapter);
		}

	}

	// 搜索框cooksearch按下键盘监听器
	class cooksearchOnkeyListener implements OnKeyListener {
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub

			if (keyCode == KeyEvent.KEYCODE_ENTER) {
				// 当按下enter 时候关闭软键盘

				InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				// cooksearch.setText("");

			}
			return false;
		}

	}

	// 搜索框cooksearch按下键盘监听器
	class cooksearchItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			try {
				TextView tv = (TextView) arg1.findViewById(R.id.serchdishname);
				TextView id = (TextView) arg1.findViewById(R.id.listid);
				String str = id.getText().toString();
				String newstr = str.substring(str.indexOf("#") + 1,
						str.length());
				int i = Integer.parseInt(newstr);
				cooksearch.setText(tv.getText().toString() + "");
				cooksearch.setSelection((cooksearch.getText().toString())
						.length());
				cooksearch.setThreshold(100);
				getinsertzuof(i);

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}

	}

	private void getinsertzuof(int i) {
		String dw = searchmaketbllist.get(i).getCook_unit();
		int sl = 0;
		if (!dw.equals("")) {
			sl = 1;
		}
		float jiag = searchmaketbllist.get(i).getCook_price();
		String mingc = searchmaketbllist.get(i).getCook_name();
		insertzuoflist(orderid, dish_id, "0", sl, jiag, dw, mingc);
		showcookselectlist();
	}

	// 搜索框autosearch按下键盘监听器
	class cooksearchOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				int curX = (int) event.getX();
				if (curX > v.getWidth() - 38
						&& !TextUtils.isEmpty(cooksearch.getText())) {
					cooksearch.setText("");
					int cacheInputType = cooksearch.getInputType();// backup the
																	// input
																	// type
					cooksearch.setInputType(InputType.TYPE_NULL);// disable soft
																	// input
					cooksearch.onTouchEvent(event);// call native handler
					cooksearch.setInputType(cacheInputType);// restore input
															// type
					return true;// consume touch even
				}
				break;
			}
			return false;
		}

	}

	// 创建做法listview按下监听事件
	class cooklistviewListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			final Cookselectholder cookselectholder = (Cookselectholder) view
					.getTag();
			final int aaa;

			aaa = position;
			cookselectholder.cookitem4
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							cookselectholder.cookitem4.startchange();
							Toast.makeText(ZuofActivity.this,
									"点击了第" + aaa + "加1按钮", Toast.LENGTH_SHORT)
									.show();
						}
					});

			cookselectholder.cookitem5
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							cookselectholder.cookitem5.startchange();
							Toast.makeText(ZuofActivity.this,
									"点击了第" + aaa + "减1按钮", Toast.LENGTH_SHORT)
									.show();
						}
					});

		}
	}

	// 创建弹出做法窗体功能按钮
	class cookviewbtnListener implements OnClickListener {

		private int tag;

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			tag = (Integer) v.getTag();

			Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90,
					v.getWidth() / 2.0f, v.getHeight() / 2.0f, 300.0f, false);
			rotation.setDuration(500);
			// rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());
			v.setAnimation(rotation);
			v.startAnimation(rotation);
			rotation.setAnimationListener(new AnimationListener() {

				private float old_num = 0;

				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {

					String flag = ordertype;
					switch (tag) {
					case 1:

						break;
					case 2:// 赠送按钮

						freedish(orderid, dish_id);
						updatecook_content(orderid, dish_id, 0);
						finish();

						break;
					case 3:
						if (pagenow >= pagetotal) {
							return;
						}
						getnextAdapter(pagenow * itemnum, itemnum);
						pagenow++;
						break;

					case 4:// 设置按钮

						String str = dishcountchange.getText().toString();

						float d = Float.parseFloat(str);
						if (d < 0) {
							Toast.makeText(ZuofActivity.this, "折扣不能小于0,请重新设置！",
									Toast.LENGTH_SHORT).show();
							dishcountchange.setText("0");
							ApkUntils.opensoftkeyboard(dishcountchange,
									powgridView, menuAdapter, 1);
						} else if (d > 100) {
							Toast.makeText(ZuofActivity.this,
									"折扣不能大于100,请重新设置！", Toast.LENGTH_SHORT)
									.show();
							dishcountchange.setText("100");
							ApkUntils.opensoftkeyboard(dishcountchange,
									powgridView, menuAdapter, 1);

						} else {
							ApkDbUntils.setupdishrate(
									getApplicationContext(), orderid, dish_id,
									str);
							updatecook_content(orderid, dish_id, 0);
							finish();
						}

						break;

					case 5:// 加1按钮

						old_num = addclick(flag, dish_id, old_num, null);
						if (!flag.equals("√")) {
							dishprice.setText(dpriflo_now + "元×" + old_num
									+ ddet_now + "="
									+ Float.parseFloat(dpriflo_now) * old_num
									+ "元");

						}

						break;
					case 6:// 减1按钮

						old_num = delclick(flag, dish_id, old_num, null);
						if (!flag.equals("√")) {
							if (old_num == 0) {
								updatecook_content(orderid, dish_id, 0);
								finish();
							} else {
								dishprice.setText(dpriflo_now + "元×" + old_num
										+ ddet_now + "="
										+ Float.parseFloat(dpriflo_now)
										* old_num + "元");
							}
						}

						break;
					case 10:
						updatecook_content(orderid, dish_id, 0);
						finish();
						break;
					default:
						break;
					}
				}
			});

		}
	}

	private void freedish(String orderid, String dish_id) {

		try {

			DishNew dish = querydish(orderid, dish_id);
			int free = dish.getFree_state();

			if (free == 0) {
				sqlstr="  update  apkpos_orders_dishs set free_state=1 where  orderid='"
						+ orderid + "' and dish_id='" + dish_id + "'  ";
			} else {
				sqlstr="  update  apkpos_orders_dishs set free_state=0 where  orderid='"
						+ orderid + "' and dish_id='" + dish_id + "'  ";
			}

			execSQL(db, mcx, sqlstr);
		} catch (Exception e) {
			Toast.makeText(ZuofActivity.this, "赠送失败！" + e.getMessage(),
					Toast.LENGTH_SHORT).show();
			Log.e("freedish", "freedish  error:" + e.getMessage());
			e.printStackTrace();
		}

	}

	private DishNew querydish(String orderid, String dish_id) {
		// TODO Auto-generated method stub
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		DishNew data = new DishNew();
		try {
			OrderTableDishs ordertabledishs = new OrderTableDishs(
					getApplicationContext());
			String selection = "orderid=? and dish_id=?";
			String selectionArgs[] = { orderid, dish_id };
			Cursor curSor = ordertabledishs.getCurSor(selection, selectionArgs);

			while (curSor.moveToNext()) {
				data = ordertabledishs.CurSorToGasBean(curSor);

			}
			curSor.close();
			// System.out.println(data);

		} catch (SQLiteException e) {
			Log.e("apkpos_orders_dish", "querydish  error:" + e.getMessage());
		}

		return data;
	}

	// 加菜函数(未落单)
	private float addclick(String flag, final String dishid, float old_num,
			final Dishpotlistholder dd) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(max(dish_num),0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		while (cursor.moveToNext()) {
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));

		}
		cursor.close();
		final float num = old_num + 1;

		if (flag.equals("√")) {

			Builder builder = new Builder(this);
			String quitMsg = "已经传到厨房,确定要进行加菜操作吗？";
			builder.setMessage(quitMsg);
			builder.setTitle(string.dialog_title1);
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setPositiveButton(string.ok,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							ApkDbUntils.changedishnum(
									getApplicationContext(), "add", 1, orderid,
									dishid);

							if (dd == null) {
								dishprice.setText(dpriflo_now + "元×" + num
										+ ddet_now + "="
										+ Float.parseFloat(dpriflo_now) * num
										+ "元");
							} else {
								dd.dishitem3.setText(num + "");
							}
							Toast.makeText(ZuofActivity.this, "增加份量成功！",
									Toast.LENGTH_SHORT).show();
						}

					});
			builder.setNegativeButton(string.cancal,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}

					});

			builder.create().show();

		} else {

			ApkDbUntils.changedishnum( getApplicationContext(), "add", 1,
					orderid, dishid);
			dishprice.setText(dpriflo_now + "元×" + num + ddet_now + "="
					+ Float.parseFloat(dpriflo_now) * num + "元");

			Toast.makeText(ZuofActivity.this, "增加份量成功！", Toast.LENGTH_SHORT)
					.show();

		}
		old_num = old_num + 1;
		return old_num;

	}

	// 减菜函数(已落单)
	private float delclick(String flag, final String dishid, float old_num,
			final Dishpotlistholder dd) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getReadableDatabase(mcx);
		}
		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(max(dish_num),0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		while (cursor.moveToNext()) {
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));

		}
		cursor.close();
		final float num = old_num - 1;
		if (num < 0) {
			Toast.makeText(ZuofActivity.this, "当前份量已经为零，无法减菜！",
					Toast.LENGTH_SHORT).show();
		} else {

			if (flag.equals("√")) {

				Builder builder = new Builder(this);
				String quitMsg = "已经传到厨房,确定要进行减菜操作吗？";
				builder.setMessage(quitMsg);
				builder.setTitle(string.dialog_title1);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setPositiveButton(string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								if (num >= 0) {
									ApkDbUntils.changedishnum(
											getApplicationContext(), "del", 1,
											orderid, dishid);
									if (dd == null) {
										dishprice.setText(dpriflo_now + "元×"
												+ num + ddet_now + "="
												+ Float.parseFloat(dpriflo_now)
												* num + "元");
									} else {
										dd.dishitem3.setText(num + "");

									}

								} else {
									updatecook_content(orderid, dish_id, 0);
									finish();
								}

								Toast.makeText(ZuofActivity.this, "减少份量成功！",
										Toast.LENGTH_SHORT).show();
							}

						});
				builder.setNegativeButton(string.cancal,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}

						});

				builder.create().show();

			} else {

				if (old_num <= 1) {
					ApkDbUntils.deletedish( getApplicationContext(),
							orderid, dishid);
					// old_num = 0;
				} else {
					ApkDbUntils.changedishnum( getApplicationContext(),
							"del", 1, orderid, dishid);
					Toast.makeText(ZuofActivity.this, "减少份量成功！",
							Toast.LENGTH_SHORT).show();

				}
			}
		}
		old_num = old_num - 1;
		return old_num;

	}
	
	public void execSQL (SQLiteDatabase db, Context mcx,String sql) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getWritableDatabase(mcx);
		}		
		db.execSQL(sql);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 加载数据
		showcooklist();		
		super.onResume();
	}


}
